-- CALC_USER_DEFENSE
-- 玩家防御（降低敌人攻击）

-- @param user    玩家对象
return function(user)
    -- 计算玩家总的降攻数值
    local defense = 0;

    -- 1. 玩家有defense属性
    local prop = PropM.combine(user, "attrib2", "defense");
    defense = PropM.apply(prop, defense);

    -- 2. 阵营增加defense
    local pet = user:getActivePet();
    local classId = pet.classId;
    local campId = CampM.getPetCamp(classId);
    prop = PropM.combine(user, "camp_defense", campId);
    defense = PropM.apply(prop, defense);

    -- 3. 按系别增加defense
    local departmentId = PetM.query(classId, "department_order")[1];
    prop = PropM.combine(user, "department_defense", departmentId);
    defense = PropM.apply(prop, defense);

    -- 4. 损血加defense
    local props = PropM.fetchProps(user, "hp_to_defense");
    for _, prop in ipairs(props) do
        defense = PropM.trigger(user, prop[1], prop[2], defense);
    end

    -- 5. 血量低于一半加defense
    prop = PropM.combine(user, "half_attrib", "defense");
    if prop[3] > 0 then
        local rate = math.modf(1000 * user:queryAttrib("hp") / user:queryAttrib("max_hp"));
        if rate < 500 then
            defense = PropM.apply(prop, defense);
        end
    end

    -- TODO: 6. 幽灵船的，暂时加在这里
    prop = GhostShipM.getShipProp("attrib2", "defense");
    if prop then
        defense = defense + PropM.apply(prop, 0);
    end

    -- TODO: 7. 英雄气概状态减少攻击
    prop = PropM.combine(user, "heroism", 1);
    if PropM.apply(prop, defense) > 0 then
        defense = defense + 3;
    end

    -- 8. 特定冈布奥降低敌人攻击+
    props = PropM.fetchProps(user, "slime_defense");
    for _, prop in ipairs(props) do
        if tonumber(prop[2]) == classId then
            defense = PropM.apply(prop, defense);
        end
    end

    return defense;
end
